#coding=utf-8
import time,sys


def getRealTime(type='GF'):
    '''Get time from time server:
    @parameter type among 'GF','GT','LF','LT'
'''
    import socket
    #时间服务器
    host = "salmon.maths.tcd.ie"
    #端口
    port = 37
    #时区
    curtz = 8
    #连接服务器,并接收返回
    try:
            host = socket.gethostbyname(host)
            s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
            s.settimeout(2)
            s.sendto("",(host,port))
            buf = s.recvfrom(10)[0]
    except socket.timeout,ex:
            return -1
    except socket.gaierror,ex:
            return -2
    except Exception,e:
            return -3
    if len(buf) < 4:
            return -4
    #计算返回的自 1900-1-1 00:00:00 的秒数
    secs = ord(buf[0])*pow(256,3)+ord(buf[1])*pow(256,2)+ord(buf[2])*pow(256,1)+ord(buf[3])
    ret = secs - 2208988800#+curtz*3600
    ##    ts = time.gmtime(secs - 2208988800+curtz*3600)
    if type == 'GF':
        return ret - curtz*3600
    elif type == 'GT':
        return time.gmtime(ret)
    elif type == 'LF':
        return ret
    elif type == 'LT':
        return time.localtime(ret)
    else:
        return -5



if __name__=='__main__':
    rt=getRealTime('LT')
    if rt > 0:
        print rt

